package com.xiangshizhineng.tianzhangzhi.app.config;

import com.alibaba.fastjson.JSONObject;
import com.xiangshizhineng.tianzhangzhi.app.model.entity.TzMes;
import com.xiangshizhineng.tianzhangzhi.app.service.MesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint("/ws/zy/{userId}") //WebSocket客户端建立连接的地址
@Component
public class WebSocketServerEndpoint {

    /**
     * 存活的session集合（使用线程安全的map保存）
     */
    private static Map<Long, Session> livingSessions = new ConcurrentHashMap<>();

    @Autowired
    MesService mesService;

    /**
     * 建立连接的回调方法
     *
     * @param session 与客户端的WebSocket连接会话
     * @param userId  用户名，WebSocket支持路径参数
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId) {
        livingSessions.put(userId, session);
       // log.info(userId + "进入连接");
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("userId") Long userId) {
        //log.info(userId + " : " + message);
        if(userId == null){
            //单发
            try{
                sendMessage(session,message);
            }catch (NullPointerException e){
                System.out.println("该用户未上线");
            }
        }else{
            //群发
            sendMessageToAll(message,userId);
        }
    }


    @OnError
    public void onError(Session session, Throwable error) {
       // log.info("发生错误");
        //log.error(error.getStackTrace() + "");
    }


    @OnClose
    public void onClose(Session session, @PathParam("userId") String userId) {
        livingSessions.remove(session.getId());
      //  log.info(userId + " 关闭连接");
    }

    /**
     * 单独发送消息
     *
     * @param session
     * @param message
     */
    public void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 群发消息
     *
     * @param message
     */
    public void sendMessageToAll(String message,Long userId) {
        TzMes messageVo = JSONObject.parseObject(message, TzMes.class);
        String type = messageVo.getType();
        if(!StringUtils.isEmpty(type)){
            mesService.save(messageVo);
        }
        livingSessions.forEach((sessionId, session) -> {
            //发给指定的接收用户
            sendMessage(session, message);
        });
    }

    public Session getSession(Long userId){
        return livingSessions.get(userId);
    }
}
